package com.javaex.book.controller;

import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.javaex.book.pojo.User;
import com.javaex.book.services.UserService;
import com.javaex.book.utils.Constants;
import com.javaex.book.utils.ReturnResult;


@Controller
@ResponseBody
@RequestMapping("/user")
public class UserController {
	
	private static final Logger logger = LoggerFactory.getLogger(UserController.class);
	
	public static final String TOKEN_KEY_IN_HEADER = "Authorization";
	
	/** 登录用户信息保存到session中时使用的key */
	public static final String LOGIN_USER_KEY_IN_SESSION = "loginUser";
	
	/** 将登录用户名保存到Cookie时使用的key */
	public static final String COOKIE_USERNAME_KEY = "username";
	
	/** cookie默认有效期为7天 */
	public static final Integer COOKIE_DEFAULT_MAX_AGE = 60 * 60 * 24 * 7;
	
	private final UserService userService;
	
	@Autowired
	public UserController(UserService userService) {
		this.userService = userService;
	}
	
	/**
	 * 获取登录用户
	 * @param session
	 * @return 登录用户信息
	 */
	@GetMapping("/login")
	public User getLoginUser(HttpSession session) {
		User user = (User) session.getAttribute(LOGIN_USER_KEY_IN_SESSION);
		logger.info("获取登录用户信息: {}", user);
		return user;
	}
	
	/**
	 * 用户登录
	 * @param user 用户登录数据
	 * @return 用户登录结果
	 */
	@PostMapping("/login")
	public ReturnResult login(@RequestBody User user, HttpServletResponse resp, HttpSession session) {
		logger.info("用户登录：username={}, password={}", user.getUsername(), user.getPassword());
		ReturnResult result = userService.login(user.getUsername(), user.getPassword());
		if (result.isSuccess()) {
			// 登录成功，将用户数据保存到session
			session.setAttribute(LOGIN_USER_KEY_IN_SESSION, result.getData());
			// 将用户名保存到Cookie中，实现免用户名登录功能
			Cookie cookie = new Cookie(COOKIE_USERNAME_KEY, user.getUsername());
			cookie.setMaxAge(COOKIE_DEFAULT_MAX_AGE);
			cookie.setPath("/");
			resp.addCookie(cookie);
		}
		return result;
	}
	
	/**
	 * 退出登录
	 */
	@GetMapping("/logout")
	public void logout(HttpSession session) {
		User loginUser = (User) session.getAttribute(LOGIN_USER_KEY_IN_SESSION);
		logger.info("退出登录: {}", loginUser);
		session.removeAttribute(LOGIN_USER_KEY_IN_SESSION);
	}
	
	/**
	 * 用户注册
	 * @param user 用户注册信息
	 * @param captcha 验证码
	 * @return 用户注册结果
	 */
	@PostMapping("/register")
	public ReturnResult register(@RequestBody User user, String captcha, HttpServletResponse resp, HttpSession session) {
		logger.info("用户注册：{}", user);
		// 比较验证码
		String token = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
		session.removeAttribute(Constants.KAPTCHA_SESSION_KEY);
		if (captcha == null || token == null || !captcha.equalsIgnoreCase(token)) {
			return ReturnResult.fail("验证码错误");
		}
		// 用户注册
		ReturnResult result = userService.register(user);
		if (result.isSuccess()) {
			// 登录成功，将用户数据保存到session
			session.setAttribute(LOGIN_USER_KEY_IN_SESSION, result.getData());
			// 将用户名保存到Cookie中，实现免用户名登录功能
			Cookie cookie = new Cookie(COOKIE_USERNAME_KEY, user.getUsername());
			cookie.setMaxAge(COOKIE_DEFAULT_MAX_AGE);
			cookie.setPath("/");
			resp.addCookie(cookie);
		}
		return result;
	}
	
	/**
	 * 修改用户信息
	 * @param user 前端提交的修改信息
	 * @return 修改结果
	 */
	@PutMapping()
	public ReturnResult updateUser(@RequestBody User user, HttpSession session) {
		logger.info("修改用户信息: {}", user);
		ReturnResult result = userService.updateUser(user);
		if (result.isSuccess()) {
			// 如果修改的是当前登录用户，修改session中的登录数据
			User loginUser = (User) session.getAttribute(LOGIN_USER_KEY_IN_SESSION);
			if (loginUser.getId() == user.getId()) {
				session.setAttribute(LOGIN_USER_KEY_IN_SESSION, user);
			}
		}
		return result;
	}
	
	/**
	 * 获取所有用户
	 * @return
	 */
	@GetMapping("/list")
	public List<User> getUserList() {
		return userService.getUserList();
	}
	
	/**
	 * 获取用户信息
	 * @param id 用户id
	 * @return 用户信息
	 */
	@GetMapping("/{id}")
	public User userDetail(@PathVariable("id") Integer id) {
		logger.info("获取用户信息：id={}", id);
		return userService.getUserById(id);
	}
	
	/**
	 * 删除用户
	 * @param id 用户id
	 * @return 删除结果
	 */
	@DeleteMapping("/{id}")
	public ReturnResult deleteUser(@PathVariable("id") Integer id) {
		logger.info("删除用户：id={}", id);
		return userService.deleteUser(id);
	}
}
